const db = require('../model/db');

// 创建商品分类
const createCategory = (req, res) => {
    const { name, description } = req.body;
    
    db.run(
        'INSERT INTO product_categories (name, description) VALUES (?, ?)',
        [name, description],
        function(err) {
            if (err) {
                return res.status(500).json({ error: '创建商品分类失败' });
            }
            res.status(201).json({
                id: this.lastID,
                name,
                description
            });
        }
    );
};

// 获取所有商品分类
const getAllCategories = (req, res) => {
    db.all('SELECT * FROM product_categories', [], (err, categories) => {
        if (err) {
            return res.status(500).json({ error: '获取商品分类失败' });
        }
        res.json(categories);
    });
};

// 创建商品
const createProduct = (req, res) => {
    const { name, category_id, price, stock, description, image_url } = req.body;
    
    db.run(
        `INSERT INTO products (name, category_id, price, stock, description, image_url, status) 
         VALUES (?, ?, ?, ?, ?, ?, 'active')`,
        [name, category_id, price, stock || 0, description, image_url],
        function(err) {
            if (err) {
                return res.status(500).json({ error: '创建商品失败' });
            }
            res.status(201).json({
                id: this.lastID,
                name,
                category_id,
                price,
                stock: stock || 0,
                description,
                image_url,
                status: 'active'
            });
        }
    );
};

// 获取商品列表
const getAllProducts = (req, res) => {
    const { category_id, status, min_price, max_price, page = 1, limit = 10 } = req.query;
    let query = 'SELECT p.*, pc.name as category_name FROM products p LEFT JOIN product_categories pc ON p.category_id = pc.id';
    let params = [];
    let conditions = [];

    if (category_id) {
        conditions.push('p.category_id = ?');
        params.push(category_id);
    }
    if (status) {
        conditions.push('p.status = ?');
        params.push(status);
    }
    if (min_price) {
        conditions.push('p.price >= ?');
        params.push(min_price);
    }
    if (max_price) {
        conditions.push('p.price <= ?');
        params.push(max_price);
    }

    if (conditions.length > 0) {
        query += ' WHERE ' + conditions.join(' AND ');
    }

    const offset = (page - 1) * limit;
    query += ` LIMIT ? OFFSET ?`;
    params.push(limit, offset);

    db.all(query, params, (err, products) => {
        if (err) {
            return res.status(500).json({ error: '获取商品列表失败' });
        }
        
        // 获取总数
        let countQuery = 'SELECT COUNT(*) as total FROM products p';
        if (conditions.length > 0) {
            countQuery += ' WHERE ' + conditions.join(' AND ');
        }
        
        db.get(countQuery, params.slice(0, -2), (err, result) => {
            if (err) {
                return res.status(500).json({ error: '获取商品总数失败' });
            }
            
            res.json({
                total: result.total,
                page: parseInt(page),
                limit: parseInt(limit),
                data: products
            });
        });
    });
};

// 获取商品详情
const getProductById = (req, res) => {
    const { id } = req.params;
    
    db.get(
        `SELECT p.*, pc.name as category_name 
         FROM products p 
         LEFT JOIN product_categories pc ON p.category_id = pc.id 
         WHERE p.id = ?`,
        [id],
        (err, product) => {
            if (err) {
                return res.status(500).json({ error: '获取商品详情失败' });
            }
            if (!product) {
                return res.status(404).json({ error: '商品不存在' });
            }
            res.json(product);
        }
    );
};

// 更新商品信息
const updateProduct = (req, res) => {
    const { id } = req.params;
    const { name, category_id, price, stock, description, image_url, status } = req.body;
    
    const updates = [];
    const params = [];
    
    if (name) {
        updates.push('name = ?');
        params.push(name);
    }
    if (category_id) {
        updates.push('category_id = ?');
        params.push(category_id);
    }
    if (price !== undefined) {
        updates.push('price = ?');
        params.push(price);
    }
    if (stock !== undefined) {
        updates.push('stock = ?');
        params.push(stock);
    }
    if (description) {
        updates.push('description = ?');
        params.push(description);
    }
    if (image_url) {
        updates.push('image_url = ?');
        params.push(image_url);
    }
    if (status) {
        updates.push('status = ?');
        params.push(status);
    }
    
    if (updates.length === 0) {
        return res.status(400).json({ error: '没有提供要更新的信息' });
    }
    
    params.push(id);
    const query = `UPDATE products SET ${updates.join(', ')} WHERE id = ?`;
    
    db.run(query, params, function(err) {
        if (err) {
            return res.status(500).json({ error: '更新商品信息失败' });
        }
        if (this.changes === 0) {
            return res.status(404).json({ error: '商品不存在' });
        }
        res.json({ message: '商品信息更新成功' });
    });
};

// 更新商品库存
const updateStock = (req, res) => {
    const { id } = req.params;
    const { stock } = req.body;

    if (stock === undefined) {
        return res.status(400).json({ error: '未提供库存数量' });
    }

    db.run(
        'UPDATE products SET stock = ? WHERE id = ?',
        [stock, id],
        function(err) {
            if (err) {
                return res.status(500).json({ error: '更新库存失败' });
            }
            if (this.changes === 0) {
                return res.status(404).json({ error: '商品不存在' });
            }
            res.json({ message: '库存更新成功' });
        }
    );
};

// 删除商品
const deleteProduct = (req, res) => {
    const { id } = req.params;
    
    db.run('DELETE FROM products WHERE id = ?', [id], function(err) {
        if (err) {
            return res.status(500).json({ error: '删除商品失败' });
        }
        if (this.changes === 0) {
            return res.status(404).json({ error: '商品不存在' });
        }
        res.json({ message: '商品删除成功' });
    });
};

module.exports = {
    createCategory,
    getAllCategories,
    createProduct,
    getAllProducts,
    getProductById,
    updateProduct,
    updateStock,
    deleteProduct
}; 